package com.example.sharesinfo.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.base.BaseUIActivity;
import com.example.sharesinfo.manager.DialogManager;
import com.example.sharesinfo.model.FlashNewsModel;
import com.example.sharesinfo.model.LongHuBangModel;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.view.DialogView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.aigestudio.datepicker.cons.DPMode;
import cn.aigestudio.datepicker.views.DatePicker;

public class LongHuBangActivity extends BaseUIActivity implements View.OnClickListener {
    private static final String LOGTAG = "LongHuBangActivity:";
    //时间选择框
    private DialogView mBirthdayDialog;
    private DatePicker mDatePicker;
    private ImageButton ib_back;
    private TextView tv_date_start;
    private TextView tv_date_end;
    //用来判断是开始还是结束
    private boolean isStart = true;
    private String startDate = "2020-3-8";
    private String endDate = "2020-3-10";
    //处理返回的code
    private static final int QUERYDATASUCCESS = 1001;
    private static final int QUERYDATAFAILED = 1002;
    //
    private static final String LogTag = "NewsFlashFragment:";
    private LinearLayout ll_dialog;
    private View item_empty_view;
    private RecyclerView mLongHuBangView;
    private SmartRefreshLayout mSrl;
    private int page = 1;
    private CommonAdapter<LongHuBangModel> mLongHuBangAdapter;
    private List<LongHuBangModel> mList = new ArrayList<>();
    private static final int MAXPAGE = 10000;
    //用来分页的数组
    private List<LongHuBangModel> mPageList = new ArrayList<>();
    //龙虎榜详情弹框
    private DialogView mDialog;
    private ImageView ib_return;
    private TextView tv_name;
    private TextView tv_time;
    private TextView tv_reason;
    private TextView tv_interpret;
    private TextView tv_jmr;
    private TextView tv_mre;
    private TextView tv_cjr;
    private TextView tv_jmrb;
    private TextView tv_cjrb;
    private LinearLayout ll_back;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case QUERYDATASUCCESS:
                    ll_dialog.setVisibility(View.GONE);
                    item_empty_view.setVisibility(View.GONE);
                    mLongHuBangView.setVisibility(View.VISIBLE);
                    JSONArray result = (JSONArray) msg.obj;
                    for (int i = 0; i < result.length(); i++) {
                        LongHuBangModel model = new LongHuBangModel();
                        try {
                            JSONObject object = (JSONObject) result.get(i);
                            model.setCode(object.getString("代码"));
                            model.setName(object.getString("名称"));
                            model.setTime(object.getString("上榜日"));
                            model.setReason(object.getString("上榜原因"));
                            model.setInterpret(object.getString("解读"));
                            model.setSpj(object.getString("收盘价"));
                            model.setZdf(object.getString("涨跌幅"));
                            model.setJmr(object.getString("龙虎榜净买额"));
                            model.setMre(object.getString("龙虎榜买入额"));
                            model.setCjr(object.getString("龙虎榜成交额"));
                            model.setZcjr(object.getString("市场总成交额"));
                            model.setJmrb(object.getString("净买额占总成交比"));
                            model.setCjrb(object.getString("成交额占总成交比"));
                            model.setHsl(object.getString("换手率"));
                            model.setLtsz(object.getString("流通市值"));
                            mList.add(model);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        getData(getPageList(mList));
                        mLongHuBangAdapter.notifyDataSetChanged();
                    }
                    break;
                case QUERYDATAFAILED:
                    item_empty_view.setVisibility(View.GONE);
                    mLongHuBangView.setVisibility(View.VISIBLE);
                    page = MAXPAGE;
                    break;
                case 404:
                    item_empty_view.setVisibility(View.VISIBLE);
                    mLongHuBangView.setVisibility(View.GONE);
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_long_hu_bang);
        initView();
        initDateDialog();
        initLongHuBangDetailDialog();
        String date = getDate();
        String[] split = date.split("-");
        tv_date_end.setText(split[0] + "年" + split[1] + "月" + split[2] + "日");
        endDate = ParDate(date);
        queryData(1, "20200401", endDate);
    }

    private void initView() {
        ll_dialog = findViewById(R.id.ll_dialog);
        ll_dialog.setVisibility(View.VISIBLE);
        item_empty_view = findViewById(R.id.item_empty_view);
        mSrl = findViewById(R.id.refreshLayout);
        mLongHuBangView = findViewById(R.id.mLongHuBangView);
        ib_back = findViewById(R.id.ib_back);
        ib_back.setOnClickListener(this);
        tv_date_start = findViewById(R.id.tv_date_start);
        tv_date_end = findViewById(R.id.tv_date_end);

        tv_date_start.setOnClickListener(this);
        tv_date_end.setOnClickListener(this);
        mSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {

                //下拉刷新
                if (mPageList.size() > 0) {
                    mPageList.clear();
                }
                refreshLayout.finishRefresh(1000);
                LogUtils.i(LogTag + "下拉刷新");
                page = 1;
                queryData(page, "20200401", endDate);
            }
        });
        //加载更多
        mSrl.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                LogUtils.i(LogTag + "加载更多" + page);
                if (page == MAXPAGE) {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                } else {
                    page++;
                    queryData(page, "20200401", endDate);
                    refreshLayout.finishLoadMore(1000);
                }

            }
        });
        mLongHuBangView.setLayoutManager(new LinearLayoutManager(this));
        mLongHuBangView.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL));
    }

    /**
     * 加载更多，将新获取的数据加入list中
     */
    private List<LongHuBangModel> getPageList(List<LongHuBangModel> pageList) {
        mPageList.addAll(pageList);
        return mPageList;
    }

    /**
     * 填充数据
     */
    private void getData(final List<LongHuBangModel> list) {
        LogUtils.i(LogTag + list.toString());
        if (list == null || list.size() == 0) {
            return;
        }
        if (mLongHuBangView == null || page == 1) {
            LogUtils.i(LogTag + "page=1");
            mLongHuBangAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<LongHuBangModel>() {
                @Override
                public void onBindViewHolder(final LongHuBangModel model, CommonViewHolder viewHolder, int type, int position) {
                    viewHolder.setText(R.id.tv_stock_name, model.getName());
                    viewHolder.setText(R.id.tv_stock_code, model.getCode());
                    viewHolder.setText(R.id.tv_stock_spj, model.getSpj());
                    viewHolder.setText(R.id.tv_stock_zdf, model.getZdf());
                    viewHolder.setText(R.id.tv_stock_hsl, model.getHsl());
                    viewHolder.setText(R.id.tv_stock_ltsz, model.getLtsz());
                    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            DialogManager.getInstance().show(mDialog);
                            tv_name.setText(model.getName());
                            tv_time.setText(model.getTime());
                            tv_reason.setText(model.getReason());
                            tv_interpret.setText(model.getInterpret());
                            tv_jmr.setText(model.getJmr());
                            tv_mre.setText(model.getMre());
                            tv_cjr.setText(model.getCjr());
                            tv_jmrb.setText(model.getJmrb());
                            tv_cjrb.setText(model.getCjrb());
                        }
                    });
                }

                @Override
                public int getLayoutId(int type) {
                    return R.layout.longhubang_item;
                }
            });
            mLongHuBangView.setAdapter(mLongHuBangAdapter);
        } else {
            mLongHuBangAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 初始化龙虎帮股票详情弹框
     */

    private void initLongHuBangDetailDialog() {
        mDialog = DialogManager.getInstance().initView(this, R.layout.dialog_longhubang_details, Gravity.CENTER);
        ib_return = mDialog.findViewById(R.id.ib_return);
        ib_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogManager.getInstance().hide(mDialog);
            }
        });
        tv_name = mDialog.findViewById(R.id.tv_name);
        tv_time = mDialog.findViewById(R.id.tv_time);
        tv_reason = mDialog.findViewById(R.id.tv_reason);
        tv_interpret = mDialog.findViewById(R.id.tv_interpret);
        tv_jmr = mDialog.findViewById(R.id.tv_jmr);
        tv_mre = mDialog.findViewById(R.id.tv_mre);
        tv_cjr = mDialog.findViewById(R.id.tv_cjr);
        tv_jmrb = mDialog.findViewById(R.id.tv_jmrb);
        tv_cjrb = mDialog.findViewById(R.id.tv_cjrb);
        ll_back = mDialog.findViewById(R.id.ll_back);
        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogManager.getInstance().hide(mDialog);
            }
        });
    }

    /**
     * 时间选择
     */
    private void initDateDialog() {
        mBirthdayDialog = DialogManager.getInstance().initView(this, R.layout.dialog_select_date, Gravity.BOTTOM);
        mDatePicker = mBirthdayDialog.findViewById(R.id.mDatePicker);
        //设置默认时间
        String nowTime = getDate();
        String[] now = nowTime.split("-");
        mDatePicker.setDate(Integer.parseInt(now[0]), Integer.parseInt(now[1]));
        //设置选择模式：单选
        mDatePicker.setMode(DPMode.SINGLE);
        mDatePicker.setOnDatePickedListener(new DatePicker.OnDatePickedListener() {

            @Override
            public void onDatePicked(String date) {
                DialogManager.getInstance().hide(mBirthdayDialog);
                String[] split = date.split("-");
                LogUtils.i(LOGTAG + isStart);
                if (isStart) {
                    startDate = ParDate(date);
                    tv_date_start.setText(split[0] + "年" + split[1] + "月" + split[2] + "日");
                    queryData(1, startDate, endDate);
                } else {
                    endDate = ParDate(date);
                    if (isJudgeDate(startDate, endDate)) {
                        tv_date_end.setText(split[0] + "年" + split[1] + "月" + split[2] + "日");
                        queryData(1, startDate, endDate);
                    } else {
                        Toast.makeText(LongHuBangActivity.this, "请选择正确的时间段", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    /**
     * 判断结束时间是否大于开始时间
     * param  开始：start
     * 结束：end
     */
    public boolean isJudgeDate(String start, String end) {
        String[] startDate = start.split("-");
        String[] endDate = end.split("-");
        if (Integer.parseInt(startDate[0]) > Integer.parseInt(endDate[0])) {
            //如果开始年份大于结束年份
            LogUtils.i(LOGTAG + "如果开始年份大于结束年份");
            return false;
        }
        if (Integer.parseInt(endDate[0]) == Integer.parseInt(startDate[0])) {
            //如果开始年份等于结束年份
            if (Integer.parseInt(startDate[1]) > Integer.parseInt(endDate[1])) {
                //如果开始月份大于结束月份
                LogUtils.i(LOGTAG + "如果开始月份大于结束月份");
                return false;
            }
            if (Integer.parseInt(endDate[1]) == Integer.parseInt(startDate[1])) {
                //如果开始月份等于结束年份
                if (Integer.parseInt(startDate[2]) > Integer.parseInt(endDate[2])) {
                    //如果开始天大于结束天
                    LogUtils.i(LOGTAG + "如果开始天大于结束天");
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 查询龙虎榜数据
     */
    public void queryData(int page, String start, String end) {
        LogUtils.i(LOGTAG + "查询数据");
        String url = "http://119.23.221.142/api/stock/GetLongHuList?BeginDate=" + start + "&EndDate=" + end + "&Page=" + page;
        LogUtils.i("链接：" + url);
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                LogUtils.i(LOGTAG + s);
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    JSONArray array = object.getJSONArray("data");
                    if (array.length() > 0) {
                        LogUtils.i(LOGTAG + "查询数据");
                        message.what = QUERYDATASUCCESS;
                        message.obj = array;
                        mHandler.sendMessage(message);
                    } else {
                        //没有跟多的分页
                        LogUtils.i(LOGTAG + "查询数据");
                        message.what = QUERYDATAFAILED;
                        mHandler.sendMessage(message);
                    }
                }
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 获取当前时间，用来填写结束时间和日历选择默认的年月
     */
    private String getDate() {
        long l = System.currentTimeMillis();
        Date date = new Date(l);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(date);
    }

    /**
     * 将日期字符串处理为api接受的格式
     */
    public String ParDate(String date) {
        String result;
        String[] str = date.split("-");
        result = str[0];
        int month = Integer.parseInt(str[1]);
        int day = Integer.parseInt(str[2]);
        if (month < 10) {
            result = result + "0" + month;
        } else {
            result = result + month;
        }
        if (day < 10) {
            result = result + "0" + day;
        } else {
            result = result + day;
        }
        return result;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_date_start:
                isStart = true;
                DialogManager.getInstance().show(mBirthdayDialog);
                break;
            case R.id.tv_date_end:
                isStart = false;
                DialogManager.getInstance().show(mBirthdayDialog);
                break;
            case R.id.ib_back:
                finish();
                break;
        }
    }
}
